package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.maof.book.model.Role;
import top.maof.book.model.User;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.result.Result;
import top.maof.book.service.UserService;
import top.maof.book.utils.JWTUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by CodeX4J.
 */
@Controller
@RequestMapping("user")
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("新建")
    @PostMapping("/create")
    public ApiResponse create(@RequestBody User user) {
        return ApiResponse.success(userService.save(user));
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        userService.removeById(id);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        userService.removeBatchByIds(idList);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody User user) {
        userService.updateById(user);
        return ApiResponse.success(null);
    }

    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<User>> findPage(@RequestBody PageWrap<User> pageWrap) {
        return ApiResponse.success(userService.findPage(pageWrap));
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID查询")
    @GetMapping("/{id}")
    public ApiResponse findById(@PathVariable Integer id) {
        return ApiResponse.success(userService.getById(id));
    }


    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    @ApiOperation("获取个人信息")
    public Result<User> find(@RequestHeader("token") String token) {
        Integer userId = JWTUtils.getUserId(token);
        User user = userService.getById(userId);
        return Result.success(user);
    }


    @Value("${img.path}")
    String imgPath;


    @ApiOperation("修改个人头像")
    @PostMapping(value = "/profile/img")
    public Result<String> img(@RequestHeader("token") String token, @RequestBody MultipartFile file) throws Exception {

        String originalFilename = file.getOriginalFilename();

        String[] split = originalFilename.split(".");

        // 后缀名
        String suffixName = split[split.length - 1].toLowerCase();

        boolean flag = suffixName.equals("png") && suffixName.equals("jpg") && suffixName.equals("jpeg");

        if (!flag) {
            return Result.response(403, "图片格式有问题");
        }

        if (file.getSize() > 1024 * 1024 * 4) {
            return Result.response(403, "图片过大");
        }
        StringBuilder sb = new StringBuilder();

        sb.append("/");

        for (char c : Integer.toHexString(originalFilename.hashCode()).toCharArray()) {
            sb.append(c).append("/");
        }

        sb.append(UUID.randomUUID().toString()).append(".").append(suffixName);

        Path path = Paths.get(imgPath, sb.toString());

        if (!Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }

        Files.createFile(path);

        file.transferTo(path);

        Integer userId = JWTUtils.getUserId(token);

        User user = new User();
        user.setId(userId);
        user.setImg(sb.toString());

        userService.updateById(user);

        return Result.success(sb.toString());
    }


}
